package com.chatplus.application.common.util;


import com.chatplus.application.common.exception.BadRequestException;

import java.io.Serializable;

/**
 * @author tan
 * @version 1.0
 * @date 2021/4/22 17:00
 */
public class PhoneNumberFormat implements Serializable {

    private static final long serialVersionUID = 982521674545790961L;

    //手机号码打马,隐藏六位
    public static String phoneFormat(String phone) {
        if (phone != null && !"".equals(phone)) {
            if (phone.length() > 5) {
                int phoneLength = phone.length();
                int midLength = phoneLength - 5;
                phone = phone.substring(0, 3) +
                    "*".repeat(midLength) +
                    phone.substring(phoneLength - 2, phoneLength);
            }
        }
        return phone;
    }

    public static String phoneWithMosaic(String phone) {
        if (phone == null || "".equals(phone)) {
            throw new BadRequestException("电话号码不能为空");
        }
        phone = phone.replaceAll("-", "").trim();
        if (phone.length() < 7) {
            throw new BadRequestException("电话号码不合法");
        }
        if (phone.length() < 11) {
            return phoneFormat(phone, 2, phone.length() - 2, 0);
        }
        if (phone.length() == 11) {
            return phoneFormat(phone, 3, phone.length() - 5, 2);
        } else {
            return phoneFormat(phone, phone.length() - 8, 6, 2);
        }
    }

    /**
     * 手机号码打码
     *
     * @param phone  明文号码
     * @param prefix 前部分展示的号码位数
     * @param mosaic 中间部分打码号码位数
     * @param suffix 后部分展示的号码位数
     * @return
     */
    public static String phoneFormat(String phone, int prefix, int mosaic, int suffix) {
        if (phone == null || phone.equals("")) {
            throw new BadRequestException("电话号码不能为空");
        }
        phone = phone.replaceAll("-", "").trim();
        int length = prefix + mosaic + suffix;
        if (phone.length() != length) {
            throw new BadRequestException("电话号码长度或入参不合法");
        }
        return phone.replaceAll("(\\d{" + prefix + "})\\d{" + mosaic + "}(\\d{" + suffix + "})", "$1" + "*".repeat(Math.max(0, mosaic)) + "$2");
    }

}
